package com.czy.owner.ui.address;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.czy.otherlib.wheelview.adapters.ListWheelAdapter;
import com.czy.otherlib.wheelview.adapters.MyCityModel;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.api.EditUserLocationApi;
import com.czy.owner.api.SaveUserLocationApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.EditUserLocationModel;
import com.czy.owner.entity.UserLocationModel;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by wangyang on 2017/5/18 0018.
 * 添加收货地址
 */

public class AddReceiverAddress extends BaseActivity {
    @BindView(R.id.et_receiver_name)
    EditText etReceiverName;
    @BindView(R.id.et_contont_phone)
    EditText etContontPhone;
    @BindView(R.id.tv_provice_city)
    TextView tvProviceCity;
    @BindView(R.id.et_address_detail)
    EditText etAddressDetail;
    @BindView(R.id.btn_sure_add)
    Button btnSureAdd;

    //    2017-9-21 wangyang新增修改
    @BindView(R.id.relative_select_city)
    RelativeLayout relativeSelectCity;
    @BindView(R.id.ll_detail_address)
    LinearLayout llDetailAddress;
    @BindView(R.id.view1)
    View view1;
    @BindView(R.id.view2)
    View view2;

    private EditUserLocationModel editUserLocationModel;

    private boolean isEdit;
    private boolean isFrom;
    private UserLocationModel.ListBean userLocationModel;
    private String userLocationId;
    private String provinceId;
    private String cityId;
    private String areaId;
    private String isDefault = "false";

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_add_receiver_address;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.add_receiver_address);
        isEdit = getIntent().getBooleanExtra("isEdit", false);
        isFrom = getIntent().getBooleanExtra("isFrom", false);
        if (isEdit) {
            userLocationModel = (UserLocationModel.ListBean) getIntent().getSerializableExtra("userLocationModel");
            etReceiverName.setText(userLocationModel.getContactUser());
            etContontPhone.setText(userLocationModel.getContact());
            tvProviceCity.setText(userLocationModel.getAddress());
            etAddressDetail.setText(userLocationModel.getDetailLocation());
            userLocationId = userLocationModel.getUserLocationId() + "";
            provinceId = userLocationModel.getProvinceId() + "";
            cityId = userLocationModel.getCityId() + "";
            areaId = userLocationModel.getAreaId() + "";
            isDefault = userLocationModel.getIsDefault();
            etReceiverName.setSelection(etReceiverName.getText().toString().length());
        }

        MyLog.e("yang","isDefault==="+isDefault);

        if (isFrom) {
            relativeSelectCity.setVisibility(View.GONE);
            llDetailAddress.setVisibility(View.GONE);
            view1.setVisibility(View.GONE);
            view2.setVisibility(View.GONE);
            getToolbarTitle().setText("添加联系人");
        }

    }

    @Override
    protected void updateViews() {

    }

    @OnClick(R.id.btn_sure_add)
    public void sureAdd(View view) {
        String contactUser = etReceiverName.getText().toString().trim();
        String contact = etContontPhone.getText().toString().trim();
        String proviceCity = tvProviceCity.getText().toString().trim();
        String detailLocation = etAddressDetail.getText().toString().trim();
        if (TextUtils.isEmpty(contactUser)) {
            PhoneUtils.ShowToastMessage(AddReceiverAddress.this, "收货人姓名不能为空");
            etReceiverName.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(contact)) {
            PhoneUtils.ShowToastMessage(AddReceiverAddress.this, "联系方式不能为空");
            etContontPhone.requestFocus();
            return;
        }

        if (!PhoneUtils.isMobileNO(contact)) {
            PhoneUtils.ShowToastMessage(AddReceiverAddress.this, "联系电话格式错误");
            etContontPhone.requestFocus();
            return;
        }


        if (!isFrom) {
            if (TextUtils.isEmpty(proviceCity)) {
                PhoneUtils.ShowToastMessage(AddReceiverAddress.this, "省市不能为空");
                return;
            }
        }


        if (!isFrom) {
            if (TextUtils.isEmpty(detailLocation)) {
                PhoneUtils.ShowToastMessage(AddReceiverAddress.this, "详细地址不能为空");
                etAddressDetail.requestFocus();
                return;
            }
        }

        if(isDefault.equals("true")){
            saveUserLocation(userLocationId, detailLocation, contact, contactUser, "true");
        }else {
            saveUserLocation(userLocationId, detailLocation, contact, contactUser, "false");
        }


    }

    @OnClick(R.id.relative_select_city)
    public void selectCity(View view) {
        list1.clear();
        list2.clear();
        list3.clear();
        getUserLocationData();
    }


    private void saveUserLocation(String userLocationId, String detailLocation, String contact, String contactUser, String isDefault) {
        SaveUserLocationApi saveUserLocationApi = new SaveUserLocationApi(new HttpOnNextListener<Integer>() {
            @Override
            public void onNext(Integer mUserLocationId) {
                MyLog.e("yang","mUserLocationId==="+mUserLocationId);
                UserLocationModel.ListBean mLocation = new UserLocationModel.ListBean();
                mLocation.setContactUser(etReceiverName.getText().toString().trim());
                mLocation.setContact(etContontPhone.getText().toString().trim());
                if(!isFrom){
                    mLocation.setDetailLocation(tvProviceCity.getText().toString().trim());
                    mLocation.setProvinceId(Integer.parseInt(provinceId));
                    mLocation.setCityId(Integer.parseInt(cityId));
                    mLocation.setAreaId(Integer.parseInt(areaId));
                }

                mLocation.setUserLocationId(mUserLocationId);

                Intent intent = new Intent();
                intent.putExtra("isEdit", isEdit);
                if(isFrom){
                    intent.putExtra("isBackToConfirmOrder", true);
                }
                intent.putExtra(Constants.TRANSMISSION_CONTENT_KEY, mLocation);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                e.printStackTrace();
                PhoneUtils.ShowToastMessage(AddReceiverAddress.this, e.getMessage());
            }
        }, this);
        saveUserLocationApi.setSession(UserHelper.getInstance().getSessionInfoModel(AddReceiverAddress.this).getSession());
        if (isEdit) {
            saveUserLocationApi.setUserLocationId(userLocationId);
        } else {
            saveUserLocationApi.setUserLocationId("");
        }
        if (!TextUtils.isEmpty(provinceId)) {
            saveUserLocationApi.setProvinceId(provinceId);
        } else {
            saveUserLocationApi.setProvinceId("");
        }

        if (!TextUtils.isEmpty(cityId)) {
            saveUserLocationApi.setCityId(cityId);
        } else {
            saveUserLocationApi.setCityId("");
        }

        if (!TextUtils.isEmpty(areaId)) {
            saveUserLocationApi.setAreaId(areaId);
        } else {
            saveUserLocationApi.setAreaId("");
        }
        if (!TextUtils.isEmpty(detailLocation)) {
            saveUserLocationApi.setDetailLocation(detailLocation);
        }else {
            saveUserLocationApi.setDetailLocation("");
        }


        saveUserLocationApi.setContact(contact);
        saveUserLocationApi.setContactUser(contactUser);
        saveUserLocationApi.setIsDefault(isDefault);
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(saveUserLocationApi);
    }


    private void getUserLocationData() {
        EditUserLocationApi editUserLocationApi = new EditUserLocationApi(new HttpOnNextListener<EditUserLocationModel>() {
            @Override
            public void onNext(EditUserLocationModel model) {
                MyLog.e("yang", "EditUserLocationApi");
                editUserLocationModel = model;
                setAddressData(editUserLocationModel);
                showDateDialog();
            }

            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                MyLog.e("yang", "cache");
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<EditUserLocationModel>>() {
                }.getType();
                BaseResultEntity<EditUserLocationModel> model = gson.fromJson(cache, type);
                editUserLocationModel = model.getData();
                setAddressData(editUserLocationModel);
                showDateDialog();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(AddReceiverAddress.this, e.getMessage());
            }
        }, this);
        editUserLocationApi.setSession(UserHelper.getInstance().getSessionInfoModel(AddReceiverAddress.this).getSession());
        editUserLocationApi.setUserLocationId("");
        HttpManager httpManager = HttpManager.getInstance();
        httpManager.doHttpDeal(editUserLocationApi);
    }


    private Dialog mDateDialog;
    private int provinceIndex = 0, cityIndex = 0;
    private List<MyCityModel> list1 = new ArrayList<>();
    private List<MyCityModel> list2 = new ArrayList<>();
    private List<MyCityModel> list3 = new ArrayList<>();

    private void setAddressData(EditUserLocationModel model) {
        list1.clear();
        if (model.getLocationList().size() > 0) {
            for (int i = 0; i < model.getLocationList().size(); i++) {
                // 获取省的list
                int locationId = model.getLocationList().get(i).getLocationId();
                String provinceName = model.getLocationList().get(i).getName();
                list1.add(new MyCityModel(locationId + "", provinceName));
            }
        }
    }

    private void showDateDialog() {
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        mDateDialog = new Dialog(AddReceiverAddress.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(AddReceiverAddress.this).inflate(R.layout.dialog_order_address, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);

        final WheelView wvAddressProvince, wvAddressCity, wvAddressArea;
        wvAddressProvince = (WheelView) dialogView.findViewById(R.id.wv_address_province);
        wvAddressCity = (WheelView) dialogView.findViewById(R.id.wv_address_city);
        wvAddressArea = (WheelView) dialogView.findViewById(R.id.wv_address_area);


        ListWheelAdapter<MyCityModel> provinceAdapter = new ListWheelAdapter<>(this, list1);
        provinceAdapter.setTextSize(16);
        wvAddressProvince.setViewAdapter(provinceAdapter);
        provinceIndex = wvAddressProvince.getCurrentItem();
        for (int i = 0; i < editUserLocationModel.getLocationList().get(provinceIndex).getSubs().size(); i++) {
            String cityCode = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(i).getLocationId() + "";
            String cityName = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(i).getName();
            list2.add(new MyCityModel(cityCode, cityName));
        }
        ListWheelAdapter<MyCityModel> cityAdapter = new ListWheelAdapter<>(AddReceiverAddress.this, list2);
        cityAdapter.setTextSize(16);
        wvAddressCity.setViewAdapter(cityAdapter);


        cityIndex = wvAddressCity.getCurrentItem();
        for (int i = 0; i < editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().size(); i++) {
            String adCode = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().get(i).getLocationId() + "";
            String cityName = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().get(i).getName();
            list3.add(new MyCityModel(adCode, cityName));

        }
        ListWheelAdapter<MyCityModel> areaAdapter = new ListWheelAdapter<>(AddReceiverAddress.this, list3);
        areaAdapter.setTextSize(16);
        wvAddressArea.setViewAdapter(areaAdapter);


        wvAddressProvince.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                list2.clear();
                list3.clear();
                provinceIndex = wvAddressProvince.getCurrentItem();
                if (editUserLocationModel.getLocationList().get(provinceIndex).getSubs().size() > 0) {
                    for (int i = 0; i < editUserLocationModel.getLocationList().get(provinceIndex).getSubs().size(); i++) {
                        String cityCode = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(i).getLocationId() + "";
                        String cityName = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(i).getName();
                        list2.add(new MyCityModel(cityCode, cityName));
                    }

                    ListWheelAdapter<MyCityModel> cityAdapter = new ListWheelAdapter<>(AddReceiverAddress.this, list2);
                    cityAdapter.setTextSize(16);
                    wvAddressCity.setViewAdapter(cityAdapter);
                }

                cityIndex = wvAddressCity.getCurrentItem();

                try {
                    if (provinceIndex == 32 || provinceIndex == 33) {
                        wvAddressArea.setViewAdapter(null);
                    }
                    if (editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().size() > 0) {
                        for (int i = 0; i < editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().size(); i++) {
                            String adCode = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().get(i).getLocationId() + "";
                            String cityName = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().get(i).getName();
                            list3.add(new MyCityModel(adCode, cityName));
                        }
                        ListWheelAdapter<MyCityModel> areaAdapter = new ListWheelAdapter<>(AddReceiverAddress.this, list3);
                        areaAdapter.setTextSize(16);
                        wvAddressArea.setViewAdapter(areaAdapter);
                    }
                } catch (Exception e) {
                    wvAddressCity.setViewAdapter(null);
                    wvAddressArea.setViewAdapter(null);
                }


            }
        });

        wvAddressCity.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                list3.clear();
                cityIndex = wvAddressCity.getCurrentItem();
                try {
                    if (editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().size() > 0) {
                        for (int i = 0; i < editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().size(); i++) {
                            String cityCode = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().get(i).getLocationId() + "";
                            String cityName = editUserLocationModel.getLocationList().get(provinceIndex).getSubs().get(cityIndex).getSubs().get(i).getName();
                            list3.add(new MyCityModel(cityCode, cityName));
                        }
                        ListWheelAdapter<MyCityModel> areaAdapter = new ListWheelAdapter<>(AddReceiverAddress.this, list3);
                        areaAdapter.setTextSize(16);
                        wvAddressArea.setViewAdapter(areaAdapter);
                    }
                } catch (Exception e) {
                    wvAddressArea.setViewAdapter(null);
                }


            }
        });


        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);
        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //省
                String province = list1.get(wvAddressProvince.getCurrentItem()).getCity_name();
                provinceId = list1.get(wvAddressProvince.getCurrentItem()).getId();

                //市
                String city = "";
                if (list2.size() > 0) {
                    city = list2.get(wvAddressCity.getCurrentItem()).getCity_name();
                    cityId = list2.get(wvAddressCity.getCurrentItem()).getId();
                } else {
                    city = "";
                    cityId = "0";
                }

                //区
                String area = "";
                if (list3.size() > 0) {
                    area = list3.get(wvAddressArea.getCurrentItem()).getCity_name();
                    areaId = list3.get(wvAddressArea.getCurrentItem()).getId();
                } else {
                    area = "";
                    areaId = "0";
                }
                MyLog.e("yang", "provinceId==" + provinceId + "\ncityId==" + cityId + "\nareaId==" + areaId);
                mDateDialog.dismiss();
                tvProviceCity.setText(province + city + area);
            }
        });
    }
}
